package com.yt.user.server.api.cms;

import com.yt.common.constant.Result;
import com.yt.user.models.vo.CaptchaVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Base64;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;

@RestController("cmsCaptchaController")
@RequestMapping("/api/admin")
@Api(tags = "管理员验证码接口")
public class CaptchaController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/captcha")
    @ApiOperation("生成四位数字图形验证码")
    public Result<CaptchaVO> generateCaptcha() throws IOException {
        // 生成4位随机数字验证码
        String captchaCode = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        
        // 生成验证码图片
        BufferedImage image = createCaptchaImage(captchaCode);
        
        // 转换为Base64
        String imageBase64 = "data:image/png;base64," + imageToBase64(image);
        
        // 生成唯一标识
        String captchaKey = UUID.randomUUID().toString();
        
        // 存入Redis，5分钟过期
        String redisKey = "captcha:" + captchaKey;
        redisTemplate.opsForValue().set(redisKey, captchaCode, 5, TimeUnit.MINUTES);
        
        // 构造返回结果
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaImage(imageBase64);
        captchaVO.setCaptchaKey(captchaKey);
        
        return Result.success(captchaVO);
    }
    
    /**
     * 创建验证码图片
     * @param captchaCode 验证码
     * @return 验证码图片
     */
    private BufferedImage createCaptchaImage(String captchaCode) {
        int width = 120;
        int height = 40;
        
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        
        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        
        // 设置边框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, width - 1, height - 1);
        
        // 画干扰线
        g.setColor(Color.GRAY);
        for (int i = 0; i < 10; i++) {
            int x1 = (int) (Math.random() * width);
            int y1 = (int) (Math.random() * height);
            int x2 = (int) (Math.random() * width);
            int y2 = (int) (Math.random() * height);
            g.drawLine(x1, y1, x2, y2);
        }
        
        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, 24));
        
        // 画验证码
        for (int i = 0; i < captchaCode.length(); i++) {
            // 设置随机颜色
            g.setColor(new Color((int) (Math.random() * 150), (int) (Math.random() * 150), (int) (Math.random() * 150)));
            
            // 设置随机旋转角度
            int angle = (int) (Math.random() * 60 - 30);
            g.rotate(Math.toRadians(angle), 20 + i * 20, 20);
            g.drawString(String.valueOf(captchaCode.charAt(i)), 20 + i * 20, 28);
            g.rotate(Math.toRadians(-angle), 20 + i * 20, 20);
        }
        
        g.dispose();
        return image;
    }
    
    /**
     * 将图片转换为Base64编码
     * @param image 图片
     * @return Base64编码字符串
     * @throws IOException IO异常
     */
    private String imageToBase64(BufferedImage image) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] bytes = baos.toByteArray();
        return Base64.getEncoder().encodeToString(bytes);
    }
}